import type { Movie, Review, PosetedReview, MovieSearchQuery} from './interfaces'
import type { MovieFetchResult } from './interfaces'
import {ElMessage} from "element-plus";
// @ts-ignore
import request from "@/axios/request.js";

export async function loadMovies(size: number): Promise<Movie[]> {
  try {
    // Use the custom Axios instance to make the API call
    const response = await request.get<MovieFetchResult>(
      //TODO: Remove the baseURL in this url
      `http://127.0.0.1:8080/api/movie/randomlist`,
      {
        params: { size },
      }
    )

    // Extract the movie list from the response
    const movieList: Movie[] = response.data
    return movieList
  } catch (error) {
    throw new Error('Failed to fetch movies')
  }
}
export async function loadReviews(movie_id: number): Promise<Review[]> {
  try {
    // Use the custom Axios instance to make the API call
      const response = await request.get<Review>(
      //TODO: Remove the baseURL in this url
        `http://127.0.0.1:8080/api/review`,
        {
          params: {
            movie_id: movie_id ,
            current: 1,
            pagesize: 999
          },
        }
      )

    // Extract the movie list from the response
    const reviews: Review[] = response.data.review_list
    return reviews
  } catch (error) {
    throw new Error('Failed to fetch reviews')
  }
}

export async function submitReview(review: PosetedReview): Promise<void> {
    await request.post<PosetedReview>(
      //TODO: Remove the baseURL in this url
      "http://127.0.0.1:8080/api/review",
      review
    ).then((res: {code:number, msg:string}) => {
      if(res.code === 200){
        alert(res.msg);
        ElMessage.success(res.msg);
      }else{
        alert(res.msg);
        ElMessage.error(res.msg);
      }
    }
  )
}

export async function searchMovies(query:MovieSearchQuery): Promise<Movie[]> {

    const response = await request.get<MovieFetchResult>(
      "http://127.0.0.1:8080/api/movie",
      {
        params: {
          ...query
        }
      }
    )

    const movieList: Movie[] = response.data.movie_list
    return movieList
  }

export async function getMovieTypes(): Promise<string[]> {
  const response = await request.get<string[]>('http://127.0.0.1:8080/api/type')
  return response.data.type_list
  }
